package puc.redes.examples.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

public class UDPClient1 {
	public static void main(String args[]) throws Exception {
		try {
			String serverHostname = new String("127.0.0.1");

			if (args.length > 0)
				serverHostname = args[0];

			BufferedReader inFromUser = new BufferedReader(
					new InputStreamReader(System.in));

			DatagramSocket clientSocket = new DatagramSocket();

			InetAddress IPAddress = InetAddress.getByName(serverHostname);
			System.out.println("Intentando la conexión " + IPAddress
					+ ") a través del puerto UDP " + 2512);

			byte[] sendData = new byte[1024];
			byte[] receiveData = new byte[1024];

			System.out.print("Introduzca mensaje: ");
			String sentence = inFromUser.readLine();
			sendData = sentence.getBytes();

			System.out.println("Enviando mensajes a " + sendData.length
					+ " bytes al servidor.");
			DatagramPacket sendPacket = new DatagramPacket(sendData,
					sendData.length, IPAddress, 2512);

			clientSocket.send(sendPacket);

			DatagramPacket receivePacket = new DatagramPacket(receiveData,
					receiveData.length);

			System.out.println("Esperando el paquete retornado");
			clientSocket.setSoTimeout(10000);

			try {
				clientSocket.receive(receivePacket);
				String modifiedSentence = new String(receivePacket.getData());

				InetAddress returnIPAddress = receivePacket.getAddress();

				int port = receivePacket.getPort();

				System.out.println("Desde el servidor en: " + returnIPAddress + ":"
						+ port);
				System.out.println("Mensaje: " + modifiedSentence);

			} catch (SocketTimeoutException ste) {
				System.out.println("Timeout: El paquete se ha perdido");
			}

			clientSocket.close();
		} catch (UnknownHostException ex) {
			System.err.println(ex);
		} catch (IOException ex) {
			System.err.println(ex);
		}
	}
}
